package com.qianfeng.springsecuriry.handler;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.springsecuriry.mapper.MenuMapper;
import com.qianfeng.springsecuriry.mapper.RoleMapper;
import com.qianfeng.springsecuriry.pojo.BaseUser;
import com.qianfeng.springsecuriry.pojo.SysMenu;
import com.qianfeng.springsecuriry.pojo.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/8/18 21:32
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RoleMapper roleMapper;

    private MenuMapper menuMapper;

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    /**
     * 登录成功后执行,我们在这里给用户重新查询权限设置给用户
     * @param request the request which caused the successful authentication
     * @param response the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     * the authentication process.
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //我们先获取到当前登录成功的用户
        BaseUser user = (BaseUser) authentication.getPrincipal();
        //然后获取用户的角色
        Long userId = user.getUserId();
        //获取用户的权限
        List<SysRole> roleList = roleMapper.findAllByUserId(userId);
        //重新设置权限
        //利用所有的角色获取到所有的权限
        List<SimpleGrantedAuthority> authorityList =
                //遍历每一个角色
                roleList.stream().flatMap(sysRole -> {
                    //用每一个角色查询到对应的菜单,把每一个角色的所有的菜单转成权限对象
            return menuMapper.findAllMenusByRoleId(sysRole.getRoleId())
                    .stream().map(SysMenu::getPerms)//获取到权限字符串
                    .map(SimpleGrantedAuthority::new);//转成权限对象

        }).collect(Collectors.toList());//将所有查询到的数据放到一个集合中
        System.err.println("登录成功后得到的用户的权限"+authorityList);
        //以当前用户和密码以及新的权限重新创建认证对象,重新设置给当前用户
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), authorityList));
    }
}
